package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.*;
import com.sc.nft.dto.AdminUserWorkRoomExportDTO;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.AddWorkRoomDTO;
import com.sc.nft.entity.dto.UserWorkRoomPageDTO;
import com.sc.nft.entity.vo.UserWorkRoomExcludeWhiteListRankVO;
import com.sc.nft.entity.vo.UserWorkRoomPageVO;
import com.sc.nft.entity.vo.WebApplicationRequirementVO;
import com.sc.nft.entity.vo.WorkRoomExportVO;
import com.sc.nft.enums.ApplicationRequirementUpOrDownEnum;
import com.sc.nft.enums.WorkCityServerAssessDetailEnum;
import com.sc.nft.enums.WorkCityServerPreAssessTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.factory.ApplicationRequirementFactory;
import com.sc.nft.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (UserWorkRoom)表服务实现类
 *
 * @author wwc
 * @since 2023-07-18 17:25:08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserWorkRoomServiceImpl implements UserWorkRoomService {

    private final UserWorkRoomDao userWorkRoomDao;

    private final UserInfoDao userInfoDao;

    private final ServiceCenterAuditDao serviceCenterAuditDao;

    private final ExpenditureRecordService expenditureRecordService;

    private final UserWalletDao userWalletDao;

    private final UserCityServerCentreDao userCityServerCentreDao;

    private final UserMarketValueService userMarketValueService;

    private final ApplicationRequirementFactory applicationRequirementFactory;

    private final ApplicationRequirementDao applicationRequirementDao;

    private final ApplicationRequirementService applicationRequirementService;

    private final ApplicationRequirementSmsService applicationRequirementSmsService;

    private final ServiceCenterAuditService  serviceCenterAuditService;
    private final UserWorkRoomDownDao  userWorkRoomDownDao;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelCommunityOutlets(Long id) {
        UserWorkRoom userWorkRoom = userWorkRoomDao.getById(id);
        if (BeanUtil.isEmpty(userWorkRoom)) {
            return Boolean.TRUE;
        }
        // 干掉网点的所有记录
        serviceCenterAuditDao.cancelCommunityOutletsRecord(userWorkRoom.getUserId(), 1);
        return userWorkRoomDao.removeById(id);
    }

    @Override
    public void addWorkRoom(AddWorkRoomDTO addWorkRoomDTO) {
        // 通过用户的手机号获取用户的数据,在通过用户的数据,获取用户是否有申请过,申请是否初审过了,如果初审过了.就把他写入到社区网点表中
        UserInfo userInfo = userInfoDao.getOneByUserTel(addWorkRoomDTO.getUserTel());
        // 判定他是不是城市服务中心
        UserCityServerCentre userCityServerCentre = userCityServerCentreDao.selectByUserId(userInfo.getId());

        if (BeanUtil.isNotEmpty(userCityServerCentre)) {
            throw new GlobalRunTimeException("当前为城市服务中心,请取消后重试");
        }
        UserWorkRoom userWorkRoom = userWorkRoomDao.selectByUserId(userInfo.getId());
        if (BeanUtil.isNotEmpty(userWorkRoom)) {
            throw new GlobalRunTimeException("当前用户已成为社区网点");
        }
        UserWorkRoom addWorkRoom = new UserWorkRoom();
        addWorkRoom.setWorkName(addWorkRoomDTO.getWorkName());
        addWorkRoom.setUserId(userInfo.getId());
        addWorkRoom.insert();
    }

    @Override
    public Page<UserWorkRoomPageVO> page(UserWorkRoomPageDTO userWorkRoomPageDTO) {
        return userWorkRoomDao.selectPageList(userWorkRoomPageDTO);
    }

    @Override
    public List<WorkRoomExportVO> workRoomExport() {
        List<WorkRoomExportVO> result = userWorkRoomDao.workRoomExport();
        for (WorkRoomExportVO vo : result) {
            UserInfo userInfo = userInfoDao.getOneByUserTel(vo.getUserTel());
            Integer validatedUser = userInfoDao.getByListUserIdCountValid(userInfo.getId(), false);
            BigDecimal teamCost = userMarketValueService.getEcologyMarketValue(userInfo.getId());
            vo.setValidatedUser(validatedUser);
            vo.setTeamCost(teamCost);
            vo.setTypeName("社区网点");
        }

        return result;
    }

    @Override
    public List<AdminUserWorkRoomExportDTO> userWorkRoomExport() {
        List<UserWorkRoom> list = userWorkRoomDao.getList();
        ArrayList<AdminUserWorkRoomExportDTO> dtoList = Lists.newArrayList();
        for (UserWorkRoom userWorkRoom : list) {
            AdminUserWorkRoomExportDTO workRoomExportDTO = userWorkRoomDao.getDataByUserId(userWorkRoom.getUserId());
            log.info("社区网点导出数据:{}", workRoomExportDTO);
            workRoomExportDTO.setUserTradeNum(workRoomExportDTO.getFirstIssueNum() > workRoomExportDTO.getSecondIssueNum() ? workRoomExportDTO.getFirstIssueNum() : workRoomExportDTO.getSecondIssueNum());
            userWorkRoomDao.insertUserWorkRoomDataTemp(workRoomExportDTO);
//            dtoList.add(workRoomExportDTO);
        }
        return dtoList;
    }

    @Override
    public List<AdminUserWorkRoomExportDTO> getDataList() {
        return userWorkRoomDao.getDataList();
    }
    /**
     * 获取排除白名单的用户
     *
     * @return
     */
    @Override
    public List<UserWorkRoomExcludeWhiteListRankVO> getUserWorkRoomExcludeWhiteListRank() {
        return userWorkRoomDao.getUserWorkRoomExcludeWhiteListRank();
    }
    /**
     * 获取所有社区网点
     *
     * @return
     */
    @Override
    public Integer getCount() {
        return userWorkRoomDao.getCount();
    }
    /**
     * 社区网点降级.
     *
     * @param userWorkRoom
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void downgrade(UserWorkRoom userWorkRoom, Long assessId) {
        if (BeanUtil.isEmpty(userWorkRoom)) {
            return;
        }
        // 获取用户数据
        UserInfo user = userInfoDao.getById(userWorkRoom.getUserId());
        // 通过用户和类型,获取用户审核资质.
        WebApplicationRequirementVO webApplicationRequirementVO = applicationRequirementService.webApplicationRequirementUserVO(user, 1);
        //  根据方法返回的结果,判断是否满足条件
        Boolean satisfy = webApplicationRequirementVO.whetherThereAreConditionsForPassing();
        // 满足,不需要降级.但是也要记录一条数据,显示他本次未降级.
        if (satisfy) {
            WorkCityServerAssessDetailLog workCityServerAssessDetailLog = new WorkCityServerAssessDetailLog();
            workCityServerAssessDetailLog.setUserId(user.getId());
            workCityServerAssessDetailLog.setAssessId(assessId);
            workCityServerAssessDetailLog.setResult(JSONObject.toJSONString(webApplicationRequirementVO));
            workCityServerAssessDetailLog.insert();
        } else {
            // 降级,并且记录降级的数据
            WorkCityServerAssessDetailLog workCityServerAssessDetailLog = new WorkCityServerAssessDetailLog();
            workCityServerAssessDetailLog.setUserId(user.getId());
            workCityServerAssessDetailLog.setAssessId(assessId);
            workCityServerAssessDetailLog.setType(WorkCityServerAssessDetailEnum.DOWN);
            workCityServerAssessDetailLog.setResult(JSONObject.toJSONString(webApplicationRequirementVO));
            workCityServerAssessDetailLog.insert();
            // 短信通知
            applicationRequirementSmsService.sendSms(user.getUserTel(),WorkCityServerAssessDetailEnum.DOWN);
            // 把该条数据干掉,但是干掉之前,要把他的数据记录降级表中,作为下次进行升级查询数据.
            userWorkRoom.deleteById();
            // 设置为空是为了让UserWorkRoomDown的id自增
            userWorkRoom.setId(null);
            UserWorkRoomDown userWorkRoomDown = BeanUtil.copyProperties(userWorkRoom, UserWorkRoomDown.class);
            userWorkRoomDown.setRemark("社区网点降级下来的用户");
            userWorkRoomDown.insert();
            //干掉所有的申请记录.让他在申请就去重新申请去
            serviceCenterAuditService.deleteByUserIdAndType(user.getId(),1);
        }
    }

    /**
     * 社区网点预降级.
     *
     * @param userWorkRoom
     */
    @Override
    public void preDowngrade(UserWorkRoom userWorkRoom) {
        if (BeanUtil.isEmpty(userWorkRoom)) {
            return;
        }
        // 获取用户数据
        UserInfo user = userInfoDao.getById(userWorkRoom.getUserId());
        // 通过用户和类型,获取用户审核资质.
        WebApplicationRequirementVO webApplicationRequirementVO = applicationRequirementService.webApplicationRequirementUserVO(user, 1);
        //  根据方法返回的结果,判断是否满足条件
        Boolean satisfy = webApplicationRequirementVO.whetherThereAreConditionsForPassing();
        // 满足,不需要降级.但是也要记录一条数据,显示他本次未降级.
        if (satisfy) {
            WorkCityServerPreAssess workCityServerPreAssess = new WorkCityServerPreAssess();
            workCityServerPreAssess.setUserId(user.getId());
            workCityServerPreAssess.setType(ApplicationRequirementUpOrDownEnum.USER_WORK_ROOM);
            workCityServerPreAssess.setAssessType(WorkCityServerPreAssessTypeEnum.NO_UP_AND_NO_DOWN);
            workCityServerPreAssess.setResult(JSONObject.toJSONString(webApplicationRequirementVO));
            workCityServerPreAssess.setPreAssessDate(new Date());
            workCityServerPreAssess.insert();
        } else {
            // 降级,并且记录降级的数据
            WorkCityServerPreAssess workCityServerPreAssess = new WorkCityServerPreAssess();
            workCityServerPreAssess.setUserId(user.getId());
            workCityServerPreAssess.setType(ApplicationRequirementUpOrDownEnum.USER_WORK_ROOM);
            workCityServerPreAssess.setAssessType(WorkCityServerPreAssessTypeEnum.DOWN);
            workCityServerPreAssess.setResult(JSONObject.toJSONString(webApplicationRequirementVO));
            workCityServerPreAssess.setPreAssessDate(new Date());
            workCityServerPreAssess.insert();
            // 短信通知
            applicationRequirementSmsService.sendPreSms(user.getUserTel(),ApplicationRequirementUpOrDownEnum.USER_WORK_ROOM);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upgrade(UserWorkRoomExcludeWhiteListRankVO userWorkRoomExcludeWhiteListRankVO, Long assessId) {
        UserWorkRoomDown userWorkRoomDown = userWorkRoomDownDao.getUserId(userWorkRoomExcludeWhiteListRankVO.getUserId());
        UserInfo user = userInfoDao.getById(userWorkRoomDown.getUserId());
        // 通过用户和类型,获取用户审核资质.
        WebApplicationRequirementVO webApplicationRequirementVO = applicationRequirementService.webApplicationRequirementUserVO(user, 1);
        //  根据方法返回的结果,判断是否满足条件
        Boolean satisfy = webApplicationRequirementVO.whetherThereAreConditionsForPassing();
        // 满足,对他进行升级.如果不满足,则也记录一条他在这次未升级的数据
        if (satisfy) {
            // 判定他是不是城市服务中心,防止用户直接申请了城市服务中心的,结果拿了双重奖励
            UserCityServerCentre userCityServerCentre = userCityServerCentreDao.selectByUserId(user.getId());
            // 是城市服务中心,直接干掉这条数据,不在升级
            if (BeanUtil.isNotEmpty(userCityServerCentre)) {
                // 哪怕删掉这一条数据也先修改一下备注,使用手动删除方式干掉这条数据
                userWorkRoomDown.setRemark("用户已经是城市服务中心了,不在对他的社区网点进行升级");
                userWorkRoomDown.updateById();
                // 干掉这条记录
                userWorkRoomDown.deleteById();
                return;
            }
            // 在升级的时候先判定这个用户是不是已经是社区网点,要考虑到他降级了,在期间达到了,又申请了并且通过了,所以如果他是社区网点的话就不在操作
            UserWorkRoom userWorkRoom = userWorkRoomDao.selectByUserId(user.getId());
            // 如果存在的话直接返回执行下一条
            if (BeanUtil.isNotEmpty(userWorkRoom)) {
                // 哪怕删掉这一条数据也先修改一下备注,使用手动删除方式干掉这条数据
                userWorkRoomDown.setRemark("用户已经是社区网点了,不在对他的社区网点进行升级");
                userWorkRoomDown.updateById();
                // 干掉这条记录
                userWorkRoomDown.deleteById();
                return;
            }
            // 不存在,新增一个新的社区网点
            UserWorkRoom addWorkRoom = new UserWorkRoom();
            addWorkRoom.setUserId(user.getId());
            addWorkRoom.setWorkName(userWorkRoomDown.getWorkName());
            addWorkRoom.insert();
            // 短信通知
            applicationRequirementSmsService.sendSms(user.getUserTel(),WorkCityServerAssessDetailEnum.UP);
            //  升级记录
            WorkCityServerAssessDetailLog workCityServerAssessDetailLog = new WorkCityServerAssessDetailLog();
            workCityServerAssessDetailLog.setUserId(user.getId());
            workCityServerAssessDetailLog.setType(WorkCityServerAssessDetailEnum.UP);
            workCityServerAssessDetailLog.setAssessId(assessId);
            workCityServerAssessDetailLog.setResult(JSONObject.toJSONString(webApplicationRequirementVO));
            workCityServerAssessDetailLog.insert();
            // 干掉这条记录
            userWorkRoomDown.deleteById();
        }else {
            // 记录一条未升级的数据
            WorkCityServerAssessDetailLog workCityServerAssessDetailLog = new WorkCityServerAssessDetailLog();
            workCityServerAssessDetailLog.setUserId(user.getId());
            workCityServerAssessDetailLog.setAssessId(assessId);
            workCityServerAssessDetailLog.setResult(JSONObject.toJSONString(webApplicationRequirementVO));
            workCityServerAssessDetailLog.insert();
        }

    }
    @Override
    public UserWorkRoom getByUserId(Long userId) {
        return userWorkRoomDao.getByUserId(userId);
    }
}
